package org.yx.service.sres.save_group_info_and_detail;

import java.util.ArrayList;
import java.util.List;

import org.dbist.dml.Query;
import org.yx.exception.BizException;
import org.yx.models.SResGrpDef;
import org.yx.models.SresDevDef;
import org.yx.models.SresGrpDev;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 保存（新增，删除，修改）资源组及其下的资源明细
 * 
 * @author zxw
 * @since 2022/04/21
 **/
public class SresSaveGroupInfoAndDetailService extends BaseService {
	public SresSaveGroupInfoAndDetailOut saveGroupInfoAndDetail(SresSaveGroupInfoAndDetailIn in) throws Exception {
		if (StrUtil.isBlank(in.getGroupCode())) {
			throw new BizException("SYS-0004", "请求的参数${parameter}要求不能为空。", FieldMap.of("parameter", "groupCode"));
		}

		SResGrpDef def = selectOneLocked(SResGrpDef.class, in.getUserOrgCode(), in.getGroupCode());
		SresSaveGroupInfoAndDetailOut out = new SresSaveGroupInfoAndDetailOut();
		if (StrUtil.equals("D", in.getStatus())) {
			if (def == null) {
				throw new BizException("BAS-0008", "数据不存在或已被删除。");
			}
			def.setGroupStatus("D");

			update(def, "groupStatus");
			return out;
		}

		if (def != null) {
			def.setGroupDesc(in.getGroupDesc());
			update(def, "groupDesc");
		} else {
			def = new SResGrpDef();
			def.setOrgCode(in.getUserOrgCode());
			def.setGroupCode(in.getGroupCode());
			def.setGroupDesc(in.getGroupDesc());
			def.setGroupStatus("N");
			insert(def);
		}

		Query query = new Query();
		query.addFilter("orgCode", def.getOrgCode());
		query.addFilter("groupCode", def.getGroupCode());
		query.addFilter("status", "N");
		List<SresGrpDev> devList = selectList(SresGrpDev.class, query);
		if (CollUtil.isNotEmpty(devList)) {
			for (SresGrpDev dev : devList) {
				dev.setStatus("D");
			}

			updateBatch(devList, "status");
		}

		if (CollUtil.isEmpty(in.getResList())) {
			return out;
		}

		devList = new ArrayList<SresGrpDev>();
		for (SresDevDef dev : in.getResList()) {
			SresGrpDev gDev = new SresGrpDev();
			gDev.setId(uuidKey());
			gDev.setGroupCode(def.getGroupCode());
			gDev.setOrgCode(def.getOrgCode());
			gDev.setResId(dev.getResId());
			gDev.setStatus("N");

			devList.add(gDev);
		}

		insertBatch(devList);

		return out;
	}
}